﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Security;
using System.Threading;
using AirLib;
using Network.Bonjour;
using System.Security.Permissions;
using System.Diagnostics;

/////////////////////////////////////////
//Notes
/////////////////////////////////////////
/*
 *This app is VERY basic.  Expect crashes if you open folders that contain odd files * 
*/


//Making use of ImageListView control
//Provided via Apache License
//http://www.opensource.org/licenses/apache2.0.php
//http://www.codeproject.com/Articles/43265/ImageListView
//

namespace AirLibClient
{
    /// <summary>
    /// Main
    /// </summary>
    public partial class Main : Form
    {
        #region Fields

        AirLib.AppleTv _appleTv;
        
        #endregion Fields      

        #region Methods

        /// <summary>
        /// Initializes a new instance of the <see cref="Main"/> class.
        /// </summary>
        public Main()
        {
            

            InitializeComponent();

           AirLib.AirplayServiceDiscovery serviceDiscovery = new AirLib.AirplayServiceDiscovery();
           serviceDiscovery.AirplayServiceFound += new AirplayServiceDiscovery.AirplayServiceFoundDelegate(serviceDiscovery_AirplayServiceFound);        

            this.Text = "AirLib Client App";
            SetUpDrivesList();
        }

        /// <summary>
        /// Services the discovery_ airplay service found.
        /// </summary>
        /// <param name="item">The item.</param>
        void serviceDiscovery_AirplayServiceFound(Network.ZeroConf.IService item)
        {
            if (cbAppleTv.InvokeRequired)
            {
                cbAppleTv.Invoke(new AirplayServiceDiscovery.AirplayServiceFoundDelegate(serviceDiscovery_AirplayServiceFound), item);
            }
            else
            {
                cbAppleTv.Items.Add(item);
                lblAppleTvStatus.Text = "Apple Tv Status: Apple Tv(s) Discovered.  Please select an Apple Tv";
            }
        }

        /// <summary>
        /// Sets up drives list.
        /// </summary>
        private void SetUpDrivesList()
        {
            
            DriveInfo[] drives = DriveInfo.GetDrives();
            foreach (var drive in drives)
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(drive.RootDirectory.FullName);
                TreeNode newDrive = new TreeNode(directoryInfo.Name);
                newDrive.Tag = drive.RootDirectory.FullName;
                FillDirectories(drive.RootDirectory.FullName, newDrive);
                tvFiles.Nodes.Add(newDrive);                
            }           
        }

        /// <summary>
        /// Handles the BeforeExpand event of the tvFiles control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.TreeViewCancelEventArgs"/> instance containing the event data.</param>
        private void tvFiles_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            if(e.Node.Nodes.Count >= 0)
            {
                foreach (TreeNode node in e.Node.Nodes)
                {
                    if (node.Nodes.Count == 0)
                    {
                        FillDirectories(node.Tag.ToString(), node);
                    }
                }
                
            }
        }
        
        /// <summary>
        /// Fill in directories
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="node">The node.</param>
        private void FillDirectories(string path, TreeNode node)
        {
            try
            {
                foreach (string directoryName in Directory.EnumerateDirectories(path))
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(directoryName);
                    TreeNode newDirectory = new TreeNode(directoryInfo.Name);
                    newDirectory.Tag = directoryInfo.FullName;
                    node.Nodes.Add(newDirectory);
                }
            }
            catch (UnauthorizedAccessException)
            {
            }
            catch (IOException)
            {
            }
        }

        /// <summary>
        /// Handles the AfterSelect event of the tvFiles control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.TreeViewEventArgs"/> instance containing the event data.</param>
        private void tvFiles_AfterSelect(object sender, TreeViewEventArgs e)
        {
            ilvPhotos.Items.Clear();
            foreach (string fileName in Directory.EnumerateFiles(e.Node.FullPath))
            {               
                FileInfo fileInfo = new FileInfo(fileName);

                switch (fileInfo.Extension.ToLower())
                {
                    case ".jpg":
                    case ".png":
                    case ".mov":
                    case ".m4v":
                    case ".avi":
                    case ".mpg":
                    case ".dvr-ms":
                    case ".mp4":
                    case ".wmv":
                    case ".bmp":
                        ilvPhotos.Items.Add(fileName);
                        break;
                }
            }

            if (ilvPhotos.Items.Count > 0)
            {
                ilvPhotos.Items[0].Selected = true;
            }

        }
       

        /// <summary>
        /// Event fired when the ImageListView selection is changed
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void SelectionChanged(object sender, EventArgs e)
        {
            if (ilvPhotos.SelectedItems.Count == 0)
                return;

            FileInfo fileInfo = new FileInfo(ilvPhotos.SelectedItems[0].FileName);

            tsslPath.Text = fileInfo.Directory.FullName;
            
            switch (fileInfo.Extension.ToLower())
            {
                case ".jpg":
                case ".png":
                case ".bmp":
                    _appleTv.ShowPhoto(fileInfo.FullName);            
                    break;
                case ".mov":
                case ".m4v":
                case ".avi":
                case ".mpg":
                case ".dvr-ms":
                case ".mp4":
                case ".wmv":
                    _appleTv.StartVideo(tvFiles.SelectedNode.FullPath.Replace(@"\", @"/") + @"/" + fileInfo.Name);
                    break;
            }
        }

        /// <summary>
        /// Handles the SelectedIndexChanged event of the cbAppleTv control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void cbAppleTv_SelectedIndexChanged(object sender, EventArgs e)
        {
            Network.ZeroConf.IService selectedAppleTv = (Network.ZeroConf.IService)cbAppleTv.SelectedItem;

            _appleTv = new AirLib.AppleTv(selectedAppleTv.Addresses[0].Addresses.First(i => i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToString(), Properties.Settings.Default.StreamHostPort);
            _appleTv.GetScreenInfo();
            tvFiles.Enabled = true;
            lblAppleTvStatus.Text = "Apple Tv Status: Connected (" + selectedAppleTv.Addresses[0].Addresses.First(i => i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToString() + ")";


            //AirLib.Slideshow slideShow = new Slideshow(selectedAppleTv.Addresses[0].Addresses.First(i => i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToString(), Properties.Settings.Default.StreamHostPort);
            //DirectoryInfo directoryInfo = new DirectoryInfo(@"D:\Pictures\2012\2012_08_25");
            //foreach (FileInfo file in directoryInfo.GetFiles("*.jpg"))
            //{
            //    slideShow.PhotoList.Add(file.FullName);
            //}

            //do
            //{
            //    Thread.Sleep(5000);
            //    slideShow.Start();
            //} while (true);

        }

        /// <summary>
        /// Handles the FormClosed event of the Main control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.FormClosedEventArgs"/> instance containing the event data.</param>
        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(0);
        }

        #endregion Methods
    }
}

